//#include "stdafx.h"
#include "getter.h"

Getter::Getter()
{
}

Getter::~Getter()
{
}

CamGetter::CamGetter()
	:capture(NULL)
{
	capture.open(0);
}

CamGetter::~CamGetter()
{
	capture.release();
}

bool CamGetter::NextImg(Mat & img)
{
	if(!IsReady())
	{
		return false;
	}
	capture >> img;
	
    if(!img.data)
	{
		return false;
	}

	return true;
}

bool CamGetter::IsReady()
{
	return capture.isOpened();
}

DirGetter::DirGetter(string const & dir_path)
	:begin_dir(dir_path),
	files_inic(false),
	first_time(true)
{
}

bool DirGetter::IsReady()
{
	if(!exists(begin_dir))
		return false;
	//if(!is_regular_file(*begin_dir))
		//return false;
	return true;
}

bool DirGetter::NextImg(Mat & img)
{
	if(!IsReady())
	{
		return false;
	}
	if(first_time)
	{
		first_time = false;
		BuildFiles(begin_dir);
		if(files_inic) 
			now_file = files.begin();
	}
	if(!files_inic)
	{
		return false;
	}
	if(now_file == files.end() )
	{
		return false;
	}
	/*
	if(img != 0)
	{
		cvReleaseImage( &img );
	}
	*/
	img = imread((*now_file++).string(),1);
	if(!img.data)
	{
		return false;
	}
	return true;
}

path DirGetter::GetNowFile()
{
	if(files_inic)
		return *now_file;
	else
	{
		return path();
	}
}

void DirGetter::BuildFiles(path now_path)
{
	if(!exists(now_path))
	{
		files_inic = false;
		return;
	}
	if(!is_directory(now_path))
	{
		files_inic = false;
		return;
	}
	PATHS all;
	copy(directory_iterator(now_path), directory_iterator(), back_inserter(all) );
	for(PATHS::iterator it(all.begin()); it != all.end(); ++it)
	{
		if(!is_directory(*it))
		{
			string ext = extension(*it);
			
			if(ext == ".jpg" || ext == ".png" || ext == ".jpeg")
				files.push_back(*it);
		}
		else
		{
			BuildFiles(*it);
			if(!files_inic)
			{
				return;
			}
		}
	}
	files_inic = true;
}

